package com.app.micaihu.view.shop;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.view.ViewCompat;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.comment.NewsComment;
import com.app.micaihu.bean.news.NewsContent;
import com.app.micaihu.configure.ActivityRequestCode;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UserConfigTools;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.custom.view.SlideSelectView;
import com.app.micaihu.custom.view.dataview.DetailNewsView;
import com.app.micaihu.custom.view.dialog.ReportDialog;
import com.app.micaihu.custom.view.listivew.CommentListView;
import com.app.micaihu.listener.CommentListener;
import com.app.micaihu.listener.HandleListener;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.AppShareUtils;
import com.app.micaihu.utils.CollectUtils;
import com.app.micaihu.utils.CommentUtils;
import com.app.micaihu.view.main.MainActivity;
import com.app.micaihu.view.newsdetail.DefaultExecutorSupplier;
import com.app.micaihu.view.newsdetail.ImageShowActivity;
import com.app.micaihu.view.newsdetail.view.DetailScrollView;
import com.app.micaihu.view.user.userinfo.activity.MyHomepageDynamicActivity;
import com.app.micaihu.view.user.userinfo.activity.WebActivity;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.app.utils.util.osutils.StatusBarUtils;
import com.app.widget.LoadView;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.ActivityUtils;
import com.facebook.common.internal.Closeables;
import com.facebook.common.memory.PooledByteBuffer;
import com.facebook.common.memory.PooledByteBufferInputStream;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.BaseDataSubscriber;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.google.gson.reflect.TypeToken;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.socialize.UMShareAPI;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by Guo on 2017/4/24.
 * <p>
 * <p>
 * 图文商品详情
 */

public class CommodityDetailActivity extends BaseOldActivity implements View.OnClickListener {
    public static boolean isShowSave = true;//是否展示引导收藏
    public static boolean isShowComment = true;//是否展示引导评论

    /*********
     * 页面控件变量
     *********/
    private DetailScrollView mScrollView;//滑动布局
    private CommentListView mCommentListView;//评论载体
    private LoadView mNewsLoadView;//文章加载提示
    private View mHeadAuthorView;//頂部作者模块
    private TextView mCommentSum;//评论总数
    private TextView mShareSum;//分享总数
    private ImageView mCollectView;//收藏
    private CommodityDetailView detailNewsView;//内容view

    /*********
     * 页面逻辑数据
     *********/
    private NewsContent mNewsContent;//页面内容
    private String newsId;//文章id
    private String pageSourceType;//来源类型 1正常列表 2相关列表 3网页 4push
    private boolean onPageFinish;//是否加载成功

    /***********
     * 页面工具
     *************/
    private CommentListener mCommentListener;//评论监听
    private AppShareUtils mShareUtils;//分享工具
    private AppShareUtils mShareUtils1;//分享工具(右上角的分享工具)
    private ReportDialog reportDialog;
    private Animation enterAnimation;
    private Animation outAnimation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //获取传输数据
        isInit = false;
        getIntentData();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commoditydetail);
        StatusBarUtils.setupStatusBarView(this, R.color.common_bg_color_2, R.color.common_bg_color_10);
        StatusBarUtils.setStatusBarTextColor(this, true);
        initView();//初始化页面
        loadData();//初始化页面数据
        querySaveNews();//查询本地收藏
    }


    /**
     * 初始化控件
     */
    private void initView() {
        this.mScrollView = (DetailScrollView) findViewById(R.id.psv_psrsolview);

        this.detailNewsView = (CommodityDetailView) findViewById(R.id.cdv_detail);
        this.detailNewsView.init();
        this.detailNewsView.httpName = mPageName;

        this.mCommentListView = (CommentListView) findViewById(R.id.prlv_listview);
        this.mNewsLoadView = (LoadView) findViewById(R.id.lv_loadview);
        this.mNewsLoadView.setErrorPageClickListener(this);
        View commentView = findViewById(R.id.tv_comment);
        mCommentSum = (TextView) findViewById(R.id.tv_commentSum);
        mShareSum = (TextView) findViewById(R.id.tv_shareSum);
        View commentLayout = findViewById(R.id.newsDetail_comment_layout);
        ViewGroup.LayoutParams params = commentView.getLayoutParams();
        params.width = ViewSizeUtils.getWidthPixels() * 3 / 7;
        commentLayout.requestLayout();
        commentLayout.invalidate();
        findViewById(R.id.iv_share).setOnClickListener(this);
        findViewById(R.id.iv_report).setOnClickListener(this);
        mCollectView = (ImageView) findViewById(R.id.iv_collect);
        mCollectView.setOnClickListener(this);
        commentView.setOnClickListener(this);
        commentLayout.setOnClickListener(this);
        findViewById(R.id.page_head_function).setOnClickListener(this);
        //配置webview
        configWebView();
    }


    /* 初始化webview */
    @SuppressLint("SetJavaScriptEnabled")
    private void configWebView() {
        if (detailNewsView != null && detailNewsView.webview != null && !detailNewsView.webview.getIsDestory()) {
            detailNewsView.webview.setWebViewClient(new CommodityDetailActivity.MyWebViewClient());
        }

    }

    /**
     * 获取传输的页面数
     */
    private void getIntentData() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        newsId = intent.getStringExtra(Config.Extra.PARAMETER1);
        pageSourceType = intent.getStringExtra(Config.Extra.PARAMETER2);
    }

    /************************ 操作数据的方法 start ******************/

    /**
     * 加载数据
     */
    private void loadData() {
        HashMap<String, String> parmsMap = new HashMap<String, String>();
        parmsMap.put("articleId", newsId + "");
        parmsMap.put("sourceType", pageSourceType + "");

        if (UserInforManager.getInstance().isLogin()) {
            parmsMap.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        }
        HttpListener<DataBean<NewsContent>> httpListener = new HttpListener<DataBean<NewsContent>>() {

            @Override
            public void onStart() {
                if (mNewsLoadView != null) {
//                    mNewsLoadView.showLoadPage();
                    mNewsLoadView.showLoadPage("");
                }
            }

            @Override
            public void onError(VolleyError error) {
                if (mNewsLoadView != null) {
                    mNewsLoadView.showErrorPage(AppApplication.getInstance().getString(R.string.neterror_click));
                }
            }

            @Override
            public void onSuccess(DataBean<NewsContent> response) {
                if (response.noError() && !isFinishing()) {
                    mNewsContent = response.getData();
                    //适配数据
                    adapterUI();
                } else {
                    mNewsLoadView.showErrorPage(response.getMsg());
                }
            }
        };
        //请求网络
        addPostCacheRequest(URIContant.NEWSDETAIL, new TypeToken<DataBean<NewsContent>>() {
        }.getType(), parmsMap, httpListener);
        // 添加js交互接口类，并起别名 imagelistner
    }

    /**
     * 适配数据
     */
    private void adapterUI() {
        if (mNewsContent == null || detailNewsView == null || detailNewsView.webview == null) {
            mNewsLoadView.showErrorPage(DataBean.getErrorMsg());
            return;
        }

        /************* 适配顶部内容页 ***********/
        // 添加js交互接口类，并起别名 imagelistner
        this.detailNewsView.webview.addJavascriptInterface(new CommodityDetailActivity.JavascriptInterface(mActivity), "imagelistner");
        //加载新闻内容
        detailNewsView.setNewsData(mNewsContent);
        if (TextUtils.equals(mNewsContent.getArticleType(), TypeConstant.NEWS_NORMAL)
                || TextUtils.equals(mNewsContent.getArticleType(), TypeConstant.NEWS_WEB)) {
            //新闻文章逻辑
            //加载页面顶部作者头像
            mHeadAuthorView = findViewById(R.id.page_head_author_layout);
            mHeadAuthorView.setOnClickListener(this);
            TextView authorView = (TextView) mHeadAuthorView.findViewById(R.id.page_head_author);
            authorView.setText(mNewsContent.getAuthorName());
            CustomImageView civ = (CustomImageView) mHeadAuthorView.findViewById(R.id.page_head_usericon);
            LoadImageUtils.getInstance().loadCircleImage(civ, mNewsContent.getAuthorHeadPic());
            /************* 适配底部评论页 ***********/
            if (!TextUtils.isEmpty(mNewsContent.getCommentNum()) && !"0".equals(mNewsContent.getCommentNum())) {
                this.mCommentSum.setText(mNewsContent.getCommentNum());
                this.mCommentSum.setVisibility(View.VISIBLE);
            }

            //设置分享数量
            if (!TextUtils.isEmpty(mNewsContent.getShareNum()) && !"0".equals(mNewsContent.getShareNum())) {
                this.mShareSum.setText(mNewsContent.getShareNum());
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) this.mShareSum.getLayoutParams();
                if (layoutParams != null) {
                    layoutParams.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
                    layoutParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
                    this.mShareSum.setLayoutParams(layoutParams);
                }
            }
        }

        //如果当前有账户登陆则显示账户的收藏状态
        if (UserInforManager.getInstance().isLogin()) {
            //判断是否收藏
            if (mNewsContent.getIsCollect()) {
                this.mCollectView.setImageResource(R.drawable.infor_tabbar_collection_vis);
                this.mCollectView.setTag(true);
            } else {
                this.mCollectView.setImageResource(R.drawable.detail_collect_black_selector);
                this.mCollectView.setTag(false);
            }
        }

        this.detailNewsView.setScrollCallback(new DetailNewsView.ScrollCallback() {


            @Override
            public void scroll(int l, int t, int oldl, int oldt) {
                scrollHeadAnimotion(t);
            }
        });
        //加载相关新闻模块
        if (mNewsContent != null) {

            detailNewsView.setAboutData(mNewsContent.getAboutList(), mNewsContent.getAdList(), mNewsContent.getTopAdInfo(), CommodityDetailActivity.this);
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (CommodityDetailActivity.this.isFinishing()) {
                    return;
                }
                //加载新闻

                if (mNewsContent != null) {
                    mCommentListView.setEmptyViewOnClickListener(CommodityDetailActivity.this);
//                    //加载评论
                    mCommentListView.startLoadData(CommodityDetailActivity.this, mNewsContent.getArticleId(), mPageName);
                }
//                if (mNewsContent != null && TextUtils.equals(mNewsContent.getArticleType(), TypeConstant.NEWS_NORMAL)) {
//                    //适配评论
//                    mCommentListView.setEmptyViewOnClickListener(CommodityDetailActivity.this);
//                    //加载评论
//                    mCommentListView.startLoadData(CommodityDetailActivity.this, mNewsContent.getArticleId(), mPageName);
//                } else if (mNewsContent != null && TextUtils.equals(mNewsContent.getArticleType(), TypeConstant.NEWS_WEB)) {
//                    //适配评论
//                    mCommentListView.setEmptyViewOnClickListener(CommodityDetailActivity.this);
//                    //加载评论
//                    mCommentListView.startLoadData(CommodityDetailActivity.this, mNewsContent.getArticleId(), mPageName);
//                } else {
//                    //禁止滑动到第二个view
//                    mScrollView.setScrollSecondView(true);
//                }
            }
        }, 1200);


    }

    /**
     * 滑动头部动画
     *
     * @param t
     */
    private void scrollHeadAnimotion(int t) {
        if (this.detailNewsView == null || mHeadAuthorView == null) {
            return;
        }
        if (t >= this.detailNewsView.getWebviewY() && mHeadAuthorView.getVisibility() == View.GONE) {

            if (enterAnimation == null) {
                enterAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                        -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
                enterAnimation.setDuration(300);
                enterAnimation.setFillAfter(true);
            }
            mHeadAuthorView.startAnimation(enterAnimation);
            mHeadAuthorView.setVisibility(View.VISIBLE);

        } else if (t < this.detailNewsView.getWebviewY() && mHeadAuthorView.getVisibility() == View.VISIBLE) {
            if (outAnimation == null) {
                outAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                        0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                        -1.0f);
                outAnimation.setDuration(300);
                outAnimation.setFillAfter(true);
            }
            mHeadAuthorView.startAnimation(outAnimation);
            mHeadAuthorView.setVisibility(View.GONE);
        }
    }

    // 注入js函数监听
    private void addImageClickListner() {
        if (detailNewsView.webview.getIsDestory()) {
            return;
        }

        try {
            // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，在还是执行的时候调用本地接口传递url过去
            detailNewsView.webview.loadUrl("javascript:(function(){"
                    + "var objs = document.getElementsByTagName(\"img\");"
                    + "var imgurl=''; " + "for(var i=0;i<objs.length;i++)  " + "{"
                    + "imgurl+=objs[i].getAttribute('data-original')+',';"
                    + "objs[i].setAttribute('myid',''+i);"
                    + "objs[i].onclick=function()  " + "    {  "
                    + "var myid=this.getAttribute('myid');"
                    + "  window.imagelistner.openImage(imgurl,myid);  " + "    }  "
                    + "}" + "})()");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // js通信接口
    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }

        @android.webkit.JavascriptInterface
        public void openImage(String img, String index) {
            Intent intent = new Intent();
            String[] imgs = img.split(",");
            ArrayList<String> imgsUrl = new ArrayList<String>();
            for (String s : imgs) {
                imgsUrl.add(s);
            }
            intent.putStringArrayListExtra(Config.Extra.PARAMETER1, imgsUrl);
            intent.putExtra(Config.Extra.PARAMETER2, Integer.valueOf(index));
            if (mNewsContent != null) {
                intent.putExtra("title", mNewsContent.getShareTitle());
            }
            intent.setClass(context, ImageShowActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            overridePendingTransition(R.anim.base_alpha_in, R.anim.base_slide_remain);// 前一个参数是下一个Activity的效果
        }
    }


    // 监听
    private class MyWebViewClient extends WebViewClient {


        /**
         * sdk20以下执行该方法
         *
         * @param view
         * @param url
         * @return
         */
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            return super.shouldInterceptRequest(view, url);

        }


//        /**
//         * sdk 20以上执行该方法
//         *
//         * @param view
//         * @param request
//         * @return
//         */
//        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
//        @Override
//        public WebResourceResponse shouldInterceptRequest(WebView view, final WebResourceRequest request) {
//            LogUtils.e("gzq", "shouldInterceptRequest = " + request.getUrl().toString());
//            return super.shouldInterceptRequest(view, request);
////            if (TextUtils.equals(mNewsContent.getArticleType(), TypeConstant.NEWS_WEB)) {
////                return super.shouldInterceptRequest(view, request);
////            }
////
////            WebResourceResponse response = null;
////            try {
////                URL imgUrl = new URL(request.getUrl().toString());
////            HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
////            conn.addRequestProperty("referer", URIContant.REALMNAME);
////            conn.setConnectTimeout(5 * 1000);
////            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
////            response = new WebResourceResponse("image/png", "UTF-8", inStream);
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
//
////                return loadImage(request.getUrl().toString());
//
//
////            WebResourceResponse response = null;
////            try {
////                LogUtils.e("gzq", "Thread = " + Thread.currentThread().getName());
////                final PipedOutputStream out = new PipedOutputStream();
////                PipedInputStream in = new PipedInputStream(out);
////                HttpUtils.addImageRequest(request.getUrl().toString(), mPageName, 0, 0, new Response.Listener<Bitmap>() {
////                    @Override
////                    public void onResponse(final Bitmap response) {
////                        LogUtils.e("gzq", "onResponse_Thread = " + Thread.currentThread().getName());
////                        new Thread(new Runnable() {
////                            @Override
////                            public void run() {
////                                LogUtils.e("gzq", "onRun_Thread = " + Thread.currentThread().getName());
////                                if (response != null) {
////                                    try {
////                                        out.write(ImageUtils.bitmap2Bytes(response, 100));
////                                        out.close();
////                                    } catch (Exception e) {
////                                        e.printStackTrace();
////                                    }
////                                }
////                            }
////                        });
////
////                    }
////                }, new Response.ErrorListener() {
////                    @Override
////                    public void onErrorResponse(VolleyError error) {
////                    }
////                });
////                response = new WebResourceResponse("image/png", "UTF-8", in);
////            } catch (Exception e) {
////                e.printStackTrace();
////            }
////
////            LogUtils.e("gzq", "return_Thread = " + Thread.currentThread().getName());
////            return response;
//        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (mNewsContent != null && TextUtils.equals(mNewsContent.getArticleType(), TypeConstant.NEWS_NORMAL)) {
                //如果是正常稿子则跳转浏览器
                Intent intent = new Intent(CommodityDetailActivity.this, WebActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
                return true;
            }

            if (TextUtils.isEmpty(url) || url.length() < 5) {
                return false;
            }

            //判断是否为http协议，如果是自定义协议则交给系统
            String httpStr = "";
            try {
                httpStr = url.substring(0, 4);
            } catch (Exception e1) {
                e1.printStackTrace();
                return false;
            }
            if (!TextUtils.isEmpty(httpStr) && !httpStr.equals("http")
                    && !httpStr.equals("https") && !httpStr.equals("abou")) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                try {
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            } else if (httpStr.equals("abou")) {
                return true;
            } else {
                if (view != null) {
                    view.loadUrl(url);
                }
                return true;
            }
        }


        @Override
        public void onPageFinished(WebView view, String url) {

            //因为 webview的onPageFinished 会执行两次
            // 所以这里逻辑处理一下 只执行一次
            if (!onPageFinish && !CommodityDetailActivity.this.isFinishing()) {

                onPageFinish = true;
                //隐藏等待提示
                mNewsLoadView.showSuccess();
                //添加JS函数
                addImageClickListner();
                detailNewsView.showAboutNews();
                //延迟1秒 判断是否出引导页面 加快新闻的展现
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (CommodityDetailActivity.this.isFinishing()) {
                            return;
                        }
                        //判断是否提示收藏--未登录，并且没显示过，
                        if (isShowSave && !AppConfigManager.getInstance().readConfig(ConfigKeyConstant.firstshow_favorite, false)
                                && !UserInforManager.getInstance().isLogin()) {
                            showFavoriteGuide();
                        } else {
                            isShowSave = false;
                        }

                        //是否展示评论引导页面
                        if (isShowComment && AppConfigManager.getInstance().readConfig(ConfigKeyConstant.firstshow_commment, true)) {
                            final FrameLayout llGuideBg = (FrameLayout) findViewById(R.id.ll_guide_bg);
                            if (llGuideBg != null) {
                                mScrollView.setOnScrollListener(new DetailScrollView.OnScrollListener() {
                                    boolean isShow = true;

                                    @Override
                                    public void onScrollChanged(int l, int t, int oldl, int oldt) {
                                        if (isShow && t >= mScrollView.firstHeight && llGuideBg != null && (llGuideBg.getVisibility() == View.GONE)) {
                                            llGuideBg.findViewById(R.id.iv_guide).setVisibility(View.GONE);
                                            //说明滚动到第二个view上了
                                            final ImageView imageView = new ImageView(CommodityDetailActivity.this);
                                            imageView.setImageResource(R.drawable.guide_comment);
                                            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                    ViewGroup.LayoutParams.MATCH_PARENT);
                                            imageView.setLayoutParams(layoutParams);
                                            imageView.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    if (llGuideBg != null) {
                                                        llGuideBg.setVisibility(View.GONE);
                                                    }
                                                }
                                            });
                                            llGuideBg.addView(imageView);
                                            llGuideBg.setVisibility(View.VISIBLE);
                                            isShow = false;
                                            AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.firstshow_commment, false);
                                            isShowComment = false;
                                        }
                                    }
                                });
                            }

                        } else {
                            isShowComment = false;
                        }
                    }
                }, 1500);
            }

        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            // progressBar.setVisibility(View.GONE);
            view.goBack();
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

    }

    /**
     * 展示收藏引导图片
     */
    private void showFavoriteGuide() {
        final View llGuideBg = findViewById(R.id.ll_guide_bg);
        findViewById(R.id.iv_guide).setOnClickListener(this);
        llGuideBg.setOnClickListener(this);
        llGuideBg.setVisibility(View.VISIBLE);
        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.firstshow_favorite, true);
        isShowSave = false;
    }


    /**
     * 查询当前文文章是否本地收藏
     */
    private void querySaveNews() {
        //如果当前用户已登录则不查询本地
        if (TextUtils.isEmpty(this.newsId) || UserInforManager.getInstance().isLogin()) {
            return;
        }
        //查询本地收藏
        boolean issave = CollectUtils.getInstance().querySaveId(this.newsId);
        if (issave) {
            this.mCollectView.setImageResource(R.drawable.infor_tabbar_collection_vis);
            this.mCollectView.setTag(true);
        } else {
            this.mCollectView.setImageResource(R.drawable.detail_collect_black_selector);
            this.mCollectView.setTag(false);
        }
    }


    /************************ 操作数据的方法 end ******************/

    /********************** 所有事件 start **********************/

    /**
     * 单机事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

        if (v == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.error_page://重新加载页面数据
                loadData();
                break;
            case R.id.newsDetail_comment_layout://点击评论总数
                swithPage();
                StatService.onEvent(CommodityDetailActivity.this, "039", "新闻底部评论总数按钮", 1);// 统计的点击
                break;
            case R.id.load_empty_page://空评论点击
                showCommentDialog();
                break;
            case R.id.tv_comment://展示评论弹窗
                showCommentDialog();
                StatService.onEvent(CommodityDetailActivity.this, "038", "新闻底部评论输入框", 1);// 统计的点击
                break;
            case R.id.iv_collect://文章收藏
                save();
                StatService.onEvent(CommodityDetailActivity.this, "037", "新闻底部收藏按钮", 1);// 统计的点击
                break;
            case R.id.page_head_function://更多按钮
                share1();
                StatService.onEvent(CommodityDetailActivity.this, "030", "新闻右上角更多", 1);// 统计的点击
                break;
            case R.id.iv_appright2://更多按钮
                share();
                StatService.onEvent(CommodityDetailActivity.this, "030", "新闻中间更多分享", 1);// 统计的点击
                break;
            case R.id.iv_share://文章分享
                share();
                StatService.onEvent(CommodityDetailActivity.this, "030", "新闻下方分享按钮", 1);// 统计的点击
                break;
            case R.id.detail_stylewechat://页面分享
            case R.id.detail_wechatmoments:
            case R.id.detail_weibo:
            case R.id.detail_qq:
                pageToshare(v);
                break;
            case R.id.iv_report://举报
                reportNews();
                break;
            case R.id.ll_guide_bg://浮层
                if (v.getVisibility() == View.VISIBLE) {
                    v.setVisibility(View.GONE);
                }
                break;
            case R.id.iv_guide://浮层登录
                if (!UserInforManager.getInstance().isLogin())
                    UserInforManager.getInstance().toLoginPage(this);
                v.setVisibility(View.GONE);
                break;
            case R.id.page_head_author_layout://打开作者主页
                toAuthorPage();
                break;

        }

    }

    /**
     * 打开作者主页
     */
    private void toAuthorPage() {
        if (mNewsContent == null) {
            return;
        }
        Intent intent = new Intent(this, MyHomepageDynamicActivity.class);
        intent.putExtra(Config.Extra.PARAMETER1, mNewsContent.getAuthorId());
        startActivity(intent);
    }


    /**
     * 举报
     */
    private void reportNews() {
        if (reportDialog == null) {
            reportDialog = new ReportDialog(mActivity);
        }
        if (mNewsContent != null) {
            reportDialog.show(mNewsContent.getArticleId(), TypeConstant.PAGE_NEWS, TypeConstant.JUBAO_NEWS);
        }
    }


    /**
     * 页面分享
     */
    private void pageToshare(View v) {
        if (v == null || v.getTag() == null) {
            return;
        }
        if (mShareUtils == null) {
            mShareUtils = new AppShareUtils(this);
        }
        String type = v.getTag().toString();
        switch (type) {
            case "1"://微信
                mShareUtils.setWXShareContent(this, mNewsContent, null);
                StatService.onEvent(this, "031", "新闻内页微信分享", 1);// 统计的点击
                break;
            case "2"://微信朋友圈
                mShareUtils.setWXCShareContent(this, mNewsContent, null);
                StatService.onEvent(this, "031", "新闻内页朋友圈分享", 1);// 统计的点击
                break;
            case "3"://微博
                mShareUtils.setSinaShareContent(this, mNewsContent);
                StatService.onEvent(this, "031", "新闻内页微博分享", 1);// 统计的点击
                break;
            case "4"://qq
                mShareUtils.setQQShareContent(this, mNewsContent, null);
                StatService.onEvent(this, "031", "新闻内页qq分享", 1);// 统计的点击
                break;
        }

    }

    /**
     * 分享
     */
    private void share() {
        if (mShareUtils == null) {
            mShareUtils = new AppShareUtils(this);
        }
        mShareUtils.showShareDialog(this.mNewsContent, TypeConstant.PAGE_NEWS_DETAIL);
    }

    /**
     * 分享
     */
    private void share1() {
        if (mShareUtils1 == null) {
            SlideSelectView.onSelectListener selectListener = new SlideSelectView.onSelectListener() {
                @Override
                public void onSelect(int textSize) {
                    UserConfigTools.textSize = textSize;
                    AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.option_textSize, UserConfigTools.textSize);
                    //初始化handler
                    if (mNewsContent == null && detailNewsView != null && detailNewsView.webview != null) {
                        return;
                    }
                    detailNewsView.webview.loadDataWithBaseURL(null, mNewsContent.getArticleContent(), "text/html", "utf-8", null);// 网页刷新
                }
            };
            mShareUtils1 = new AppShareUtils(this, selectListener);
            mShareUtils1.setHandleListener(new HandleListener() {
                @Override
                public void handleStart(ArrayList<Object> parms) {

                }

                @Override
                public void handleFail(ArrayList<Object> parms) {

                }

                @Override
                public void handleSuccess(ArrayList<Object> parms) {

                }

                @Override
                public void changeView(ArrayList<Object> parms) {
                    mShareUtils1.cancleDialog();
                    tooleReadMode();
                    //通知主页面改变UI
                    ArrayList<Object> parms1 = new ArrayList<>();
                    parms1.add(TypeConstant.HANDLER_TYPE_1);
                    parms1.add(false);//不再改变资源配置
                    EventBus.getDefault().post(parms1);
                }
            });
        }
        mShareUtils1.showShareDialog(this.mNewsContent, TypeConstant.PAGE_NEWS_DETAIL1);

    }


    /**
     * 收藏
     */
    private void save() {
        if (this.mCollectView == null) {
            ToastUtils.makeText(R.drawable.handle_fail, "操作失败");
            return;
        }
        Object isSave = this.mCollectView.getTag();//获取是否收藏标识
        if (isSave == null || !((boolean) isSave)) {
            //如果没有收藏 则 进行收藏操作
            boolean b = CollectUtils.getInstance().saveNews(newsId);
            if (b) {
                ToastUtils.makeText(R.drawable.infor_pop_collection_yes, "收藏成功");
                this.mCollectView.setImageResource(R.drawable.infor_tabbar_collection_vis);
                this.mCollectView.setTag(true);
            } else {
                ToastUtils.makeText(R.drawable.handle_fail, "操作失败");
            }
        } else {
            //如果已收藏 则 进行取消操作
            boolean b = CollectUtils.getInstance().deleteSaveNews(newsId);
            if (b) {
                ToastUtils.makeText(R.drawable.infor_pop_collection_cancel, "取消收藏");
                this.mCollectView.setImageResource(R.drawable.detail_collect_black_selector);
                this.mCollectView.setTag(false);
            } else {
                ToastUtils.makeText(R.drawable.handle_fail, "操作失败");
            }
        }

    }


    /* 展示评论框 */
    private void showCommentDialog() {
        if (mNewsContent == null || TextUtils.equals(mNewsContent.getArticleType(), TypeConstant.NEWS_SHOP)) {
            //如果是电商文章不让评论
            return;
        }
        if (mCommentListener == null) {
            mCommentListener = new CommentListener() {
                @Override
                public void commentStart() {

                }

                @Override
                public void commentFail(VolleyError volley) {

                }

                @Override
                public void commentSuccess(NewsComment newsComment) {
                    //更新页面
                    if (mCommentListView != null) {
                        mCommentListView.addComment(newsComment);
                    }
                    if (mCommentSum != null) {
                        int num = StringUtils.toInt(mCommentSum.getText().toString(), 0);
                        mCommentSum.setText("" + (++num));
                        if (mCommentSum.getVisibility() == View.GONE) {
                            mCommentSum.setVisibility(View.VISIBLE);
                        }
                    }
                }
            };
        }
        CommentUtils.getInstance().showDialog(this, mPageName, newsId, null, mCommentListener);
    }

    /**
     * 改变阅读模式
     */
    public void tooleReadMode() {
        mShareUtils1 = null;
        mShareUtils = null;
        reportDialog = null;
        mCommentListener = null;
        onPageFinish = false;
        //获取传输数据
        setContentView(R.layout.activity_commoditydetail);

        StatusBarUtils.setupStatusBarView(this, R.color.common_bg_color_2, R.color.common_bg_color_10);
        ViewCompat.requestApplyInsets(findViewById(R.id.container));
        StatusBarUtils.setStatusBarTextColor(this, true);
        initView();//初始化页面
        loadData();//初始化页面数据
        querySaveNews();//查询本地收藏
    }


    /**
     * 切换页面
     */
    private void swithPage() {

        if (mScrollView == null || detailNewsView == null || mNewsContent == null || !onPageFinish) {
            return;
        }
        if (TextUtils.equals(mNewsContent.getArticleType(), TypeConstant.NEWS_SHOP)) {
            //如果是电商文章则不让跳转评论
            return;
        }
        if (mScrollView.currentPositon == 0) {
            mScrollView.scrollToSecondView();
            scrollHeadAnimotion(1000);//只要大于webview的y坐标就行
        } else {
            mScrollView.scrollToFirstView();
            scrollHeadAnimotion(this.detailNewsView.getScrollY());
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        try {
            if (data != null) {
                UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (requestCode == Config.ResultCode.REQUESTCODE_1
                && resultCode == RESULT_OK && mCommentListView != null && data != null) {
            //改变点赞数
            mCommentListView.notifyZanData(data.getBooleanExtra(Config.Extra.PARAMETER1, false));
        } else if (requestCode == ActivityRequestCode.REQUEST_CODE_USERHOME
                && resultCode == RESULT_OK && data != null && detailNewsView != null) {
            String attentionStatu = data.getStringExtra(Config.Extra.PARAMETER1);
            detailNewsView.changeAttentionState(attentionStatu);

        }


    }

    @Override
    protected void onDestroy() {
        CommentUtils.getInstance().dismissDialog();
        if (this.detailNewsView != null) {
            detailNewsView.webview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //销毁webview
            this.detailNewsView.destoryWebview();
        }
        super.onDestroy();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (this.detailNewsView != null) {
            //继续webview
            this.detailNewsView.resumeWebview();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (this.detailNewsView != null) {
            //暂停webview
            this.detailNewsView.stopWebview();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            if (detailNewsView != null && detailNewsView.webview != null
                    && detailNewsView.webview.canGoBack()) {
                detailNewsView.webview.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {

        if (ActivityUtils.isActivityExistsInStack(MainActivity.class)) {
            super.onBackPressed();
        } else {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }


    /***********************
     * 所有事件 end
     **********************/
    public WebResourceResponse loadImage(final String url) {

        WebResourceResponse response = null;
//

        ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
                .setProgressiveRenderingEnabled(false)
                .build();
        ImagePipeline imagePipeline = Fresco.getImagePipeline();


        try {
            final PipedOutputStream out = new PipedOutputStream();

            PipedInputStream in = new PipedInputStream(out);

            DataSource<CloseableReference<PooledByteBuffer>> dataSource = imagePipeline.fetchEncodedImage(imageRequest, this);
            dataSource.subscribe(new BaseDataSubscriber<CloseableReference<PooledByteBuffer>>() {
                @Override
                protected void onNewResultImpl(DataSource<CloseableReference<PooledByteBuffer>> dataSource) {
                    if (!dataSource.isFinished()) {
                        return;
                    }
                    CloseableReference<PooledByteBuffer> result = dataSource.getResult();
                    if (result != null) {
                        PooledByteBuffer pooledByteBuffer = result.get();
                        PooledByteBufferInputStream sourceIn = new PooledByteBufferInputStream(pooledByteBuffer);


                        try {
                            FileOutputStream fileOutputStream = new FileOutputStream(AppConfigTools.APKFLODER + AppConfigTools.SPREARATOR + url.substring(url.lastIndexOf("/") + 1));

                            byte[] b = new byte[1024];
                            int n;
                            try {
                                while ((n = sourceIn.read(b)) != -1) {
                                    fileOutputStream.write(b, 0, n);
                                }

                            } catch (IOException e) {
                                e.printStackTrace();
                            } finally {
                                Closeables.closeQuietly(sourceIn);
                                CloseableReference.closeSafely(result);
                                result = null;
                            }
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }

                    }

                }

                @Override
                protected void onFailureImpl(DataSource<CloseableReference<PooledByteBuffer>> dataSource) {
                }
            }, supplier.forBackgroundTasks());
            response = new WebResourceResponse("image/png", "UTF-8", in);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }


    private DefaultExecutorSupplier supplier = new DefaultExecutorSupplier(8);

}
